#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

// int main()
// {
//     int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    
//     sockaddr_in reciver;
//     memset(&reciver,0,sizeof(reciver));
//     reciver.sin_family = AF_INET;
//     reciver.sin_addr.s_addr = INADDR_ANY;
//     reciver.sin_port = htons(9090);
//     bind(sockfd,(const sockaddr *)&reciver,sizeof(reciver));

//     while(true)
//     {
//         char buffer[1024] = {0};
//         int recv_len = recvfrom(sockfd,buffer,sizeof(buffer)-1,0,NULL,0);
//         buffer[recv_len] = 0;
//         printf("接收到数据: %s\n",buffer);
//     }
//     close(sockfd);
//     return 0;
// }


int main()
{
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    
    // 加入多播组
    struct ip_mreq join;
    join.imr_interface.s_addr = htonl(INADDR_ANY);
    join.imr_multiaddr.s_addr = inet_addr("224.1.1.2");

    // 旧
    // join.imr_interface.s_addr = inet_addr("224.1.1.2");
    // join.imr_multiaddr.s_addr = htonl(INADDR_ANY);
    
    setsockopt(sockfd,IPPROTO_IP,IP_ADD_MEMBERSHIP,&join,sizeof(join));

    sockaddr_in reciver;
    memset(&reciver,0,sizeof(reciver));
    reciver.sin_family = AF_INET;
    reciver.sin_addr.s_addr = htonl(INADDR_ANY);
    reciver.sin_port = htons(9090);
    bind(sockfd,(const sockaddr *)&reciver,sizeof(reciver));

    while(true)
    {
        char buffer[1024] = {0};
        int recv_len = recvfrom(sockfd,buffer,sizeof(buffer)-1,0,NULL,0);
        buffer[recv_len] = 0;
        printf("接收到数据: %s\n",buffer);
    }
    close(sockfd);
    return 0;
}
